package main

import (
	"github.com/gin-gonic/gin/binding"
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()
	dataBind(router)
	router.Run(":8000")
}

type Math struct {
	Op1      float64 `form:"op1" json:"op1" binding:"required"`
	Op2      float64 `form:"op2" json:"op2" binding:"required"`
	Operator string  `form:"operator" json:"operator" binding:"required"`
	Result   float64 `form:"result" json:"result"`
	Error    string  `form:"error" json:"error"`
}

func dataBind(router *gin.Engine) {
	router.POST("/calc", func(c *gin.Context) {

		var req Math
		var err error
		contentType := c.Request.Header.Get("Content-Type")

		// 根据内容类型进行不同的绑定
		switch contentType {
		case "application/json":
			err = c.BindJSON(&req)
		case "application/x-www-form-urlencoded":
			err = c.ShouldBindWith(&req, binding.Form)
		default:
			req.Error = "不支持的内容类型: " + contentType
			c.JSON(http.StatusBadRequest, req)
			return
		}

		// 更高级的自动判定内容类型
		//err = c.Bind(&user)

		if err != nil {
			req.Error = "解析请求失败: " + err.Error()
			c.JSON(http.StatusBadRequest, req)
			return
		}

		switch req.Operator {
		case "add":
			req.Result = req.Op1 + req.Op2
		case "minus":
			req.Result = req.Op1 - req.Op2
		case "multiply":
			req.Result = req.Op1 * req.Op2
		case "div":
			req.Result = req.Op1 / req.Op2
		default:
			req.Error = "未知的运算符: " + req.Operator
			c.JSON(http.StatusBadRequest, req)
			return
		}

		c.JSON(http.StatusOK, req)
	})
}
